/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.os;

import java.util.*;
import javax.servlet.*;
import java.lang.reflect.*;
import bw.util.*;

public class ObjectStore 
{
    private static Object _lock = new Object();
    private static ObjectStore _instance = null;

    private MemoryCache _memCache = null;

    private PersistentObjectReader _reader = null;
    private PersistentObjectWriter _writer = null;

    //ObjectStore is a persistent cache for objects
    //There is an in-memory cache for quick access
    //backed by a persistence layer that can be 
    //remote or local. 

    public static ObjectStore getInstance()
    {
        if ( _instance == null )
        {
            synchronized ( _lock )
            {
                if ( _instance == null )
                {
                    _instance = new ObjectStore();
                }
            }
        }

        return _instance;
    }

    protected ObjectStore ()
    {
        //nothing
    }

    public void init ( ServletContext context ) throws Exception
    {
        //create the memory cache
        if ( "true".equalsIgnoreCase( context.getInitParameter( "google.appengine.enabled" ) ) )
        {
            //expire objects after a day at least
            _memCache = new GoogleMemCache( 24 * 60 * 60 );
        }
        else
        {
            //expire objects after 2 hours
            _memCache = new ExpiringHashtable( "ObjectStore_MemCache", 2 * 60 * 60 * 1000L );
        }
        _memCache.start();

        Class [] constArgs = new Class [] { Class.forName( "javax.servlet.ServletContext" ) };
        Object [] constArgsObj = new Object [] { context }; 

        //create the reader object
        String readerClassname = context.getInitParameter( "objectStore.reader.classname" );
        Class readerClass = Class.forName( readerClassname );
        Constructor readerConstructor = readerClass.getConstructor( constArgs );
        _reader = (PersistentObjectReader) readerConstructor.newInstance( constArgsObj );

        //create the writer object
        String writerClassname = context.getInitParameter( "objectStore.writer.classname" );
        Class writerClass = Class.forName( writerClassname );
        Constructor writerConstructor = writerClass.getConstructor( constArgs );
        _writer = (PersistentObjectWriter) writerConstructor.newInstance( constArgsObj );
    }

    public void setReader ( PersistentObjectReader reader ) { _reader = reader; }
    public void setWriter ( PersistentObjectWriter writer ) { _writer = writer; }

    public void put ( String key, Object obj )
        throws Exception
    {
        //store it in memory
        if ( _memCache != null )
        {
            _memCache.put( key, obj );
        }

        //and make it persistent
        _writer.write( key, obj );
    }

    public Object get ( String key )
        throws Exception
    {
        Object obj = null;
        if ( _memCache != null )
        {
            obj = _memCache.get( key );
        }

        //if the obj is not in memory then try to
        //get it from the gettin place
        if ( obj == null )
        {
            obj = _reader.read( key );
            if ( obj != null && _memCache != null )
            {
                _memCache.put( key, obj );
            }
        }

        return obj;
    }

    public void remove ( String key )
        throws Exception
    {
        if ( _memCache != null ) 
        {
            _memCache.remove( key );
        }
        _writer.erase( key );
    }

    public MemoryCache getMemoryCache ()
    {
        return _memCache;
    }

    public void shutdown ()
        throws Exception
    {
        //note ObjectStore can be used in a read only mode or write only mode
        if ( _reader != null )
        {
            _reader.shutdown();
        }

        if ( _writer != null )
        {
            _writer.shutdown();
        }
        
        if ( _memCache != null )
        {
            _memCache.shutdown();
        }

        Log.getInstance().write( "ObjectStore: Shutdown." );
    }

}